/**
 * 
 */
package com.qq.spirit;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.qq.spirit.CampaignTask.PreCampaignAction;
import com.qq.spirit.inter.AbstractActionAfterHttpRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

/**
 * 采集
 * 
 * @author beedoorwei
 * 
 */
public class PickSpaceTask extends TaskUnit
{
	public PickSpaceTask()
	{
		this.username = "采集";
	}

	@Override
	public void doTask()
	{
		try
		{
			Iterator<String> ite = UserCache.userQueue.keySet().iterator();
			while (ite.hasNext())
			{
				String username = ite.next();
				TaskManager.addTask(new PickSpace(username), GameUtil.randomInt(10));
			}
		} catch (Exception e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * 采集
	 * 
	 * @author Administrator
	 * 
	 */
	class PickSpace extends TaskUnit
	{
		public PickSpace(String username)
		{
			this.username = username;
		}

		public void doTask()
		{
			try
			{
				UserData u = UserCache.get(username);
				if (u.getUserState() == UserState.LOGIN_GAME)
				{
					// 查询采集数据
					HttpUtil.doGet(username, GameConstants.OUTCITY_GET_PICKSPACE, new PrePickSpaceAction(username));
				} else
				{
					// 添加登录任务先
					TaskManager.addTask(new LoginTask(username, this));
				}
			} catch (Exception e)
			{
				LoggerUtil.error(e);
			}
		}
	}

	/**
	 * 采集前查询
	 * 
	 * @author Administrator
	 * 
	 */
	class PrePickSpaceAction extends AbstractActionAfterHttpRequest
	{
		public PrePickSpaceAction(String username)
		{
			super();
			this.username = username;
			this.taskUnit = new PickSpace(username);
		}

		public void doCall(List<NameValuePair> headerList, XmlNodeData PickSpaceInfo)
		{
			doPickSpace(PickSpaceInfo);
		}

		/**
		 * 获取所有队列
		 * 
		 * @param PickSpaceInfo
		 * @return
		 */
		private List<XmlNodeData> getNewarestPick(XmlNodeData PickSpaceInfo)
		{
			List<XmlNodeData> tempNode = XmlDataUtil.getNodeInfoList(PickSpaceInfo, "results.playerpickdto.endtime");
			Collections.sort(tempNode, new Comparator<XmlNodeData>()
			{
				@Override
				public int compare(XmlNodeData o1, XmlNodeData o2)
				{
					int ct = GameUtil.convertInt(o1.getNodeValue());
					int ct2 = GameUtil.convertInt(o2.getNodeValue());
					if (ct <= ct2)
					{
						return -1;
					} else
					{
						return 0;
					}
				}
			});
			return tempNode;
		}

		/**
		 * 外城任务开始
		 */
		private void doPickSpace(XmlNodeData PickSpaceInfo)
		{
			List<XmlNodeData> nationTeamList = getNewarestPick(PickSpaceInfo);
			if (nationTeamList.isEmpty())
			{
				LoggerUtil.logger(UserCache.getGameName(username) + "目前没有可以收集的采集工人");
			} else
			{
				XmlNodeData xdata = nationTeamList.get(0);

				int t = GameUtil.convertInt(xdata.getNodeValue());
				if (t == 0)
				{
					LoggerUtil.logger(UserCache.getGameName(username) + "开始收集矿石");
					// 可以搞
					List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
					nvpList.add(new NameValuePair("advance", "0"));
					nvpList.add(new NameValuePair("safePick", "0"));
					nvpList.add(new NameValuePair("pickSpaceId", XmlDataUtil.getNodeData(xdata.getParent(), "id")));
					HttpUtil.doPost(username, GameConstants.OUTCITY_DO_PICKSPACE, nvpList, new PickSpaceAction(username));
				} else
				{
					LoggerUtil.logger(UserCache.getGameName(username) + "目前没有可以收取的矿石,将在," + GameUtil.getRemainTime(t + "") + "后开始收集");

					TaskManager.addTask(this.taskUnit, t / 1000 + 1);
					// 看看当前是否有空闲工人,如果有,则开始采集或者精炼

					String spacefree = XmlDataUtil.getNodeData(PickSpaceInfo, "results.spacefree");
					String maxspacefree = XmlDataUtil.getNodeData(PickSpaceInfo, "results.maxspacefree");
					String workernum = XmlDataUtil.getNodeData(PickSpaceInfo, "results.workernum");
					LoggerUtil.logger(UserCache.getGameName(username) + "当前拥有空闲工人：" + workernum + "个");
					int fnum = GameUtil.convertInt(workernum);
					if (fnum > 0)
					{
						// 判断是否有精炼次数，如果有精炼次数，则优先精炼，否则只采集
						UserData u = UserCache.get(username);
						int refineTimes = u.getRefineTimes();
						if (refineTimes > 10)
						{
							// 超过10次了，留3个工人精炼，否则一直采集下去
							if (u.getIsInRefine().get() == false)
							{
								u.getIsInRefine().set(true);
								fnum = fnum - 3;
							}
						}

						if (fnum > 0)
						{
							// 提交派遣工人任务
							TaskManager.addTask(new Pick(username, fnum), GameUtil.randomInt(10));
						}
					}
				}

			}
		}
	}

	/**
	 * 采集
	 * 
	 * @author Administrator
	 * 
	 */
	class Pick extends TaskUnit
	{
		int pickNum = 0;

		public Pick(String username, int pickNum)
		{
			this.username = username;
			this.pickNum = pickNum;
		}

		public void doTask()
		{
			try
			{
				if (pickNum > 0)
				{
					// 搞一个工人出来，去采集
					List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
					// 目前默认蒙古战役
					nvpList.add(new NameValuePair("workerNum", "1"));
					HttpUtil.doPost(username, GameConstants.OUTCITY_START_PICKSPACE, nvpList, new PickSpaceStartAction(username, pickNum));
				}
			} catch (Exception e)
			{
				LoggerUtil.error(e);
			}
		}
	}

	/**
	 * 采集后处理对象
	 * 
	 * @author Administrator
	 * 
	 */
	class PickSpaceAction extends AbstractActionAfterHttpRequest
	{
		public PickSpaceAction(String username)
		{
			super();
			this.username = username;
			this.taskUnit = new PickSpace(username);
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData PickSpaceAttackInfo)
		{
			// 获取攻击结果
			String upprofit = XmlDataUtil.getNodeData(PickSpaceAttackInfo, "results.upprofit");
			String bowlder = XmlDataUtil.getNodeData(PickSpaceAttackInfo, "results.playerupdateinfo.bowlder");
			// String freeworknum = XmlDataUtil.getNodeData(PickSpaceAttackInfo,
			// "results.playerupdateinfo.freeworknum");
			LoggerUtil.info(UserCache.getGameName(username) + "采集获得:" + upprofit + " 原石,目前原石个数为:" + bowlder);
			// 提交5秒钟后刷新
			TaskManager.addTask(taskUnit, GameUtil.randomInt(10));
		}
	}

	/**
	 * 开始采集事件
	 * 
	 * @author Administrator
	 * 
	 */
	class PickSpaceStartAction extends AbstractActionAfterHttpRequest
	{
		int pickNum = 0;

		public PickSpaceStartAction(String username, int pickNum)
		{
			super();
			this.pickNum = pickNum;
			this.username = username;
			if (pickNum <= 1)
			{
				this.taskUnit = new PickSpace(username);
			} else
			{
				this.taskUnit = new Pick(username, pickNum - 1);
			}
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData PickSpaceInfo)
		{
			LoggerUtil.info(UserCache.getGameName(username) + "派遣1个工人采集成功");
			// 提交5秒钟后刷新任务,如果成功刷新等待开始攻击，否则重新采集任务
			TaskManager.addTask(taskUnit, GameUtil.randomInt(10));
		}
	}
}
